package com.junge.javafx;

import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import com.junge.jedis.JedisTool;
import com.junge.jedis.UserInfo;
import com.junge.jedis.UserInfoTool;
import com.junge.utils.AESCryptoSecurity;
import com.junge.utils.JacksonUtil;
import com.junge.utils.NetTools;
import com.junge.utils.StringUtil;

import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Labeled;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.stage.Stage;

/**
 * 类描述 :
 * @author xiaojun.yin
 * @version 1.0
 * 2019年1月23日 下午8:20:46
 */
public class HelloWorldController implements Initializable {
	
	@FXML
	private TextField timeFmt;
	@FXML
	private TextField timeLong;
	@FXML
	private TextField timeInputLong;
	@FXML
	private TextField timeInputFmt;
	@FXML
	private TextField timeOutLong;
	@FXML
	private TextField timeOutFmt;
	@FXML
	private Button changeBtn;
	@FXML
	private TextArea logStr;
	@FXML
	private TextField userAccount;
	@FXML
	private TextField userPwd;
	@FXML
	private TextField deviceIdInput;
	@FXML
	private TextField deviceIdOut;
	@FXML
	private Labeled currentEnir;
	@FXML
	private ChoiceBox<String> userOption;
	
	private Thread timeThread;
	
	private String message;
	
	private AtomicBoolean start = new AtomicBoolean(true);
	
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	private static ExecutorService threadPool = new ThreadPoolExecutor(5, 10, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(50), new ThreadPoolExecutor.DiscardPolicy());
	
	private static String appSecret="c9596887fdd844499e0f53a6af39044f";
	
	@Override
	public void initialize(URL paramURL, ResourceBundle paramResourceBundle) {
		timeFmt.setText(sdf.format(new Date()));
		timeLong.setText(String.valueOf(System.currentTimeMillis()));
		timeSpanStart();
		timeOutFmt.setEditable(false);
		timeOutLong.setEditable(false);
		timeFmt.setEditable(false);
		timeLong.setEditable(false);
		logStr.setEditable(false);
		message = "";
		loadUserSelect();
//		List<String> userNames = UserInfoTool.getAllUserNames();
//		userOption.setItems(FXCollections.observableArrayList(userNames));
		userOption.getSelectionModel().selectedItemProperty().addListener(listener->{
			String selectStr = userOption.getSelectionModel().getSelectedItem();
			if(StringUtil.isEmpty(selectStr)){
				System.out.println("我触发了事件,值还未装载！");
				return ;
			}
			if("手动输入".equals(selectStr)){
				userAccount.setEditable(true);
				userPwd.setEditable(true);
			}else{
				userAccount.setEditable(false);
				userPwd.setEditable(false);
			}
			UserInfo userInfo = UserInfoTool.checkOutUserInfo(selectStr);
			if(userInfo == null){
				showLogMessage("请输入账户和密码！");
			}else{
				userAccount.setText(userInfo.getAccount());
				userPwd.setText(userInfo.getPwd());
			}
		});
	}
	/**
	 * 方法功能描述 :
	 * @author xiaojun.yin
	 * 2019年2月18日 下午8:33:40
	 */
	private void loadUserSelect() {
		List<String> userNames = UserInfoTool.getAllUserNames();
		System.out.println(JacksonUtil.ObjectToJsonString(userNames));
		userOption.setItems(FXCollections.observableArrayList(userNames));
	}
	/**
	 * 方法功能描述 :
	 * @author xiaojun.yin
	 * 2019年1月24日 上午10:00:07
	 */
	public void showTimes(ActionEvent ae) {
		String dateFmt = sdf.format(new Date());
		String dateLong = System.currentTimeMillis()+"";
		timeFmt.setText(dateFmt);
		timeLong.setText(dateLong);
		cropStringToBoard(dateLong);

	}
	public void exitClick(ActionEvent ae) {
		 Stage stage = (Stage)changeBtn.getScene().getWindow();
		 DialogShowMessage.showExitMessage(stage);
	}
	public void timeToLong(ActionEvent ae) {
		try{
			String fmt = timeInputFmt.getText();
			Date date = sdf.parse(fmt);
			timeOutLong.setText(String.valueOf(date.getTime()));
		}catch (Exception e) {
			String msg = "您输入的时间格式错误!正确格式为(yyyy-MM-dd HH:mm:ss)";
			DialogShowMessage.showWarningMessage(msg);
		}
		
	}
	public void timeToFmtStr(ActionEvent ae) {
		try{
			String fmt = timeInputLong.getText();
			Date date = new Date(Long.valueOf(fmt));
			timeOutFmt.setText(sdf.format(date));
		}catch (Exception e) {
			String msg = "您输入的时间戳格式错误!正确格式如：(1539779015365)";
			DialogShowMessage.showWarningMessage(msg);
		}
	}
	public void emptyLong(ActionEvent ae) {
		timeInputFmt.setText("");
		timeOutLong.setText("");
	}
	public void emptyFmtStr(ActionEvent ae) {
		timeInputLong.setText("");
		timeOutFmt.setText("");
	}
	public void synchronizationToken(ActionEvent ae) {
		JedisTool.synchronizationNeiWangToKaFa(this);
	}
	public void clearLogStr(ActionEvent ae) {
		message = "";
		logStr.setText(message);
	}
	
	public void timeStart(ActionEvent ae) {
		start.set(true);
	}
	public void timeStop(ActionEvent ae) {
		start.set(false);
	}

	@FXML
	void serachForDeviceList(ActionEvent event) {
		String account = userAccount.getText();
		String pwd = userPwd.getText();
		if(StringUtil.isEmpty(account) || StringUtil.isEmpty(pwd)){
			showLogMessage("用户名或密码不能为空");return;
		}
		showLogMessage("查询中，请稍后..........");
		threadPool.execute(new Runnable() {
			public void run() {
				try{
				String deviceInfo = NetTools.getMyDeviceList(account,pwd);
				showLogMessage(deviceInfo);
				}catch (Exception e) {
					showLogMessage(e.getMessage());
				}
			}
		});
	}
	@FXML
	void aboutSoftWare(ActionEvent event) {
		clearLogStr(event);
		String about = "制作：技术开发部\n作者：大漠孤风\n版本号：1.0.3\n发布时间：2019-02-26\n版权所有，翻版必究";
		showLogMessage(about);
	}
	@FXML
	void serachForTokenAndId(ActionEvent event) {
		String account = userAccount.getText();
		String pwd = userPwd.getText();
		if(StringUtil.isEmpty(account) || StringUtil.isEmpty(pwd)){
			showLogMessage("用户名或密码不能为空");return;
		}
		showLogMessage("查询中，请稍后..........");
		threadPool.execute(new Runnable() {
			public void run() {
				try{
				UserInfo userInfo = JedisTool.getUserTokenInfo(account,pwd);
				showLogMessage(userInfo.toString());
				}catch (Exception e) {
					showLogMessage(e.getMessage());
				}
			}
		});
	}
	@FXML
	void accountLogin(ActionEvent event) {
		String account = userAccount.getText();
		String pwd = userPwd.getText();
		if(StringUtil.isEmpty(account) || StringUtil.isEmpty(pwd)){
			showLogMessage("用户名或密码不能为空");
			return;
		}
		showLogMessage("查询中，请稍后..........");
		threadPool.execute(new Runnable() {
			public void run() {
				try{
					String result = NetTools.login(account,pwd);
					showLogMessage(result);
				}catch (Exception e) {
					e.printStackTrace();
					showLogMessage(e.getMessage());
				}
			}
		});
	}
	
	@FXML
	void clearAccontInfo(ActionEvent event) {
		userAccount.setText("");
		userPwd.setText("");
	}
	
	@FXML
	void reloadUserInfoFromTxt(ActionEvent event) {
		showLogMessage(UserInfoTool.reloadUserInfo());
		loadUserSelect();
	}
	@FXML
	void copyCurrentTime(ActionEvent event) {
		String str = timeLong.getText();
		cropStringToBoard(str);
		
	}
	@FXML
	void initToDP(ActionEvent event) {
		JedisTool.changeEnir(0);
		NetTools.changeEnir(0);
		currentEnir.setText("当前环境：测试");
		reloadUserInfoFromTxt(event);
	}
	@FXML
	void initToPre(ActionEvent event) {
		JedisTool.changeEnir(1);
		NetTools.changeEnir(1);
		currentEnir.setText("当前环境：预发布");
		reloadUserInfoFromTxt(event);
	}
	@FXML
	void initToDevelope(ActionEvent event) {
		JedisTool.changeEnir(2);
		NetTools.changeEnir(2);
		currentEnir.setText("当前环境：开发");
		reloadUserInfoFromTxt(event);
	}
	
	
	@FXML
	void emptyDeviceIdInfo(ActionEvent event) {
		deviceIdInput.setText("");
		deviceIdOut.setText("");
	}
	@FXML
	void deviceIdDecode(ActionEvent event) {
		String inputStr = deviceIdInput.getText();
		if(StringUtil.isEmpty(inputStr)){
			DialogShowMessage.showWarningMessage("请输入要转换的值");
			return;
		}
		if("E1CA60E1A71890FEBAC76D874736DB55".length() != inputStr.length()){
			DialogShowMessage.showWarningMessage("参数长度错误");
			return;
		}
		try{
			String str = AESCryptoSecurity.decrypt(inputStr, appSecret);
			deviceIdOut.setText(str);
			cropStringToBoard(str);
		}catch (Exception e) {
			String msg = "您输入DeviceId不正确！";
			DialogShowMessage.showWarningMessage(msg);
			showLogMessage(msg);
		}
	}
	@FXML
	void deviceIdEncode(ActionEvent event) {
		String inputStr = deviceIdInput.getText();
		if(StringUtil.isEmpty(inputStr)){
			DialogShowMessage.showWarningMessage("请输入要转换的值");
			return;
		}
		if(inputStr.length()>"1321312346478".length()){
			DialogShowMessage.showWarningMessage("参数长度错误");
			return;
		}
		try{
			String str = AESCryptoSecurity.encrypt(inputStr, appSecret);
			deviceIdOut.setText(str);
			cropStringToBoard(str);
		}catch (Exception e) {
			String msg = "您输入DeviceId不正确！";
			DialogShowMessage.showWarningMessage(msg);
			showLogMessage(msg);
		}
	}

	 
	private void timeSpanStart() {
		timeThread = new Thread(new Runnable() {
			public void run() {
				int sleep = 990;int x =0;
				while(true){
					try {
						if(x ==0){
							Thread.sleep(3*1000);
							x ++;
						}else{
							Thread.sleep(sleep);
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					if(start.get()){
						timeFmt.setText(sdf.format(new Date()));
						timeLong.setText(String.valueOf(System.currentTimeMillis()));
					}
				}
			}
		});
		timeThread.start();
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	/**
	 * 方法功能描述 :
	 * @author xiaojun.yin
	 * 2019年1月27日 下午2:11:34
	 * @param string
	 */
	public void showLogMessage(String msg) {
		msg = msg+"\n";
		logStr.insertText(logStr.getText().length(), msg);	
		message += msg;
		
	}
	/**
	 * 方法功能描述 :
	 * @author xiaojun.yin
	 * 2019年2月19日 下午1:22:42
	 * @param str
	 */
	private void cropStringToBoard(String str) {
		if(StringUtil.isEmpty(str)){
			showLogMessage("无可复制内容！");
			return ;
		}
		Clipboard clipboard = Clipboard.getSystemClipboard();
		ClipboardContent cc = new ClipboardContent();
		cc.putString(str);
		clipboard.setContent(cc);
		showLogMessage("已复制内容："+str);
		
	}
}
